package link.chengguo.orangemall.fms.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import link.chengguo.orangemall.ams.entity.AmsAgent;
import link.chengguo.orangemall.ams.entity.AmsBusinessCity;
import link.chengguo.orangemall.ams.mapper.AmsBusinessCityMapper;
import link.chengguo.orangemall.ams.service.IAmsAgentService;
import link.chengguo.orangemall.annotation.SysLog;
import link.chengguo.orangemall.enums.AllEnum;
import link.chengguo.orangemall.fms.entity.FmsAgentWithdraw;
import link.chengguo.orangemall.fms.service.IFmsAgentWithdrawService;
import link.chengguo.orangemall.sys.entity.SysUser;
import link.chengguo.orangemall.util.EasyPoiUtils;
import link.chengguo.orangemall.util.UserUtils;
import link.chengguo.orangemall.utils.CommonResult;
import link.chengguo.orangemall.utils.ValidatorUtils;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @author yzb
 * @date 2020-02-10
 * 代理提现
 */
@Slf4j
@RestController
@RequestMapping("/fms/fmsAgentWithdraw")
public class FmsAgentWithdrawController {

    @Resource
    private IFmsAgentWithdrawService IFmsAgentWithdrawService;
    @Resource
    private IAmsAgentService agentService;
    @Resource
    private AmsBusinessCityMapper businessCityMapper;

    @SysLog(MODULE = "fms", REMARK = "根据条件查询所有代理提现列表")
    @ApiOperation("根据条件查询所有代理提现列表")
    @GetMapping(value = "/list")
    public Object getFmsAgentWithdrawByPage(FmsAgentWithdraw entity,
                                            @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize
    ) {
        try {

            if (UserUtils.getCurrentMember().getPlatform().equals(AllEnum.PlatformType.Tenant.code())){
                QueryWrapper queryWrapper=new QueryWrapper<>();
                if (entity.getKeyword()!=null && !"".equals(entity.getKeyword())){
                    queryWrapper.apply("( member_phone like '%"+entity.getKeyword()+"%'  or member_name like '%"+entity.getKeyword()+"%')");
                }
                if (entity.getStartTime()!=null && entity.getEndTime()!=null){
                    queryWrapper.ge("create_time",entity.getStartTime());
                    queryWrapper.le("create_time",entity.getEndTime()+" 23:59:59");
                }
                if (entity.getTransferResult()!=null){
                    queryWrapper.eq("transfer_result",entity.getTransferResult());
                }
                return new CommonResult().success(IFmsAgentWithdrawService.page(new Page<>(pageNum, pageSize), queryWrapper));
            }else if(UserUtils.getCurrentMember().getPlatform().equals(AllEnum.PlatformType.Agent.code())){
                SysUser user= UserUtils.getCurrentMember();
                entity.setCityCode(user.getCityCode());
                return new CommonResult().success(IFmsAgentWithdrawService.page(new Page<FmsAgentWithdraw>(pageNum, pageSize), new QueryWrapper<>(entity).orderByDesc("id")));
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("根据条件查询所有代理提现列表：%s", e.getMessage(), e);
        }
        return new CommonResult().failed();
    }

    /**
     * 商家提现审核接口
     * @return
     */
    @SysLog(MODULE = "fms", REMARK = "提现审核操作")
    @ApiOperation("提现审核操作")
    @PostMapping(value = "/withdrawVerify")
    public Object withdrawVerify(@RequestBody FmsAgentWithdraw agentWithdraw) {
        try {
            if (IFmsAgentWithdrawService.withdrawVerify(agentWithdraw.getTransferResult(),agentWithdraw.getId(),
                    agentWithdraw.getKeyword(),agentWithdraw.getTranferDesc())) {
                return new CommonResult().success();
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("提现审核操作：%s", e.getMessage(), e);
            return new CommonResult().failed(e.getMessage());
        }
        return new CommonResult().failed();
    }

    @SysLog(MODULE = "fms", REMARK = "保存代理提现")
    @ApiOperation("保存代理提现")
    @PostMapping(value = "/create")
    public Object saveFmsAgentWithdraw(@RequestBody FmsAgentWithdraw entity) {
        try {
            if(UserUtils.getCurrentMember().getPlatform().equals(AllEnum.PlatformType.Agent.code())){
                SysUser user= UserUtils.getCurrentMember();
                entity.setCityCode(user.getCityCode());
                //查询商家信息
                AmsAgent agent =agentService.getAgentByCityCode(user.getCityCode());
                entity.setAgentName(agent.getName());
                entity.setAgentPhone(agent.getPhone());
                //添加城市名称
                AmsBusinessCity businessCity=new AmsBusinessCity();
                businessCity.setBusinessDistrict(user.getCityCode());
                AmsBusinessCity city= businessCityMapper.selectOne(new QueryWrapper<>(businessCity));
                entity.setCityName(city.getBusinessCityName());
            }
            if (IFmsAgentWithdrawService.save(entity)) {
                return new CommonResult().success();
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("保存代理提现：%s", e.getMessage(), e);
            return new CommonResult().failed(e.getMessage());
        }
        return new CommonResult().failed();
    }

    @SysLog(MODULE = "fms", REMARK = "更新代理提现")
    @ApiOperation("更新代理提现")
    @PostMapping(value = "/update/{id}")
    public Object updateFmsAgentWithdraw(@RequestBody FmsAgentWithdraw entity) {
        try {
            if(UserUtils.getCurrentMember().getPlatform().equals(AllEnum.PlatformType.Agent.code())){
                SysUser user= UserUtils.getCurrentMember();
                entity.setCityCode(user.getCityCode());
            }
            if (IFmsAgentWithdrawService.updateById(entity)) {
                return new CommonResult().success();
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("更新代理提现：%s", e.getMessage(), e);
            return new CommonResult().failed(e.getMessage());
        }
        return new CommonResult().failed();
    }

    @SysLog(MODULE = "fms", REMARK = "删除代理提现")
    @ApiOperation("删除代理提现")
    @GetMapping(value = "/delete/{id}")
    public Object deleteFmsAgentWithdraw(@ApiParam("代理提现id") @PathVariable Long id) {
        try {
            if (ValidatorUtils.empty(id)) {
                return new CommonResult().paramFailed("代理提现id");
            }
            if (IFmsAgentWithdrawService.removeById(id)) {
                return new CommonResult().success();
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("删除代理提现：%s", e.getMessage(), e);
            return new CommonResult().failed(e.getMessage());
        }
        return new CommonResult().failed();
    }

    @SysLog(MODULE = "fms", REMARK = "给代理提现分配代理提现")
    @ApiOperation("查询代理提现明细")
    @GetMapping(value = "/{id}")
    public Object getFmsAgentWithdrawById(@ApiParam("代理提现id") @PathVariable Long id) {
        try {
            if (ValidatorUtils.empty(id)) {
                return new CommonResult().paramFailed("代理提现id");
            }
            FmsAgentWithdraw coupon = IFmsAgentWithdrawService.getById(id);
            return new CommonResult().success(coupon);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("查询代理提现明细：%s", e.getMessage(), e);
            return new CommonResult().failed();
        }

    }

    @ApiOperation(value = "批量删除代理提现")
    @RequestMapping(value = "/delete/batch", method = RequestMethod.GET)
    @SysLog(MODULE = "fms", REMARK = "批量删除代理提现")
    public Object deleteBatch(@RequestParam("ids") List
            <Long> ids) {
        boolean count = IFmsAgentWithdrawService.removeByIds(ids);
        if (count) {
            return new CommonResult().success(count);
        } else {
            return new CommonResult().failed();
        }
    }


    @SysLog(MODULE = "fms", REMARK = "导出社区数据")
    @GetMapping("/exportExcel")
    public void export(HttpServletResponse response, FmsAgentWithdraw entity) {
        // 模拟从数据库获取需要导出的数据
        List<FmsAgentWithdraw> personList = IFmsAgentWithdrawService.list(new QueryWrapper<>(entity).orderByDesc("id"));
        // 导出操作
        EasyPoiUtils.exportExcel(personList, "导出社区数据", "社区数据", FmsAgentWithdraw.class, "导出社区数据.xls", response);

    }

    @SysLog(MODULE = "fms", REMARK = "导入社区数据")
    @PostMapping("/importExcel")
    public void importUsers(@RequestParam MultipartFile file) {
        List<FmsAgentWithdraw> personList = EasyPoiUtils.importExcel(file, FmsAgentWithdraw.class);
        IFmsAgentWithdrawService.saveBatch(personList);
    }
}


